import React from "react";
import ReactDOM from "react-dom";
import { SketchPicker } from "react-color"
import "./index.less";

const containerClass = "visbar-gui-color-picker-wrapper";
class ColorPickerBase extends React.Component<any> {
    wrapper: HTMLDivElement;
    constructor(props) {
        super(props);
        this.initWrapper();
        this.wrapper.style.top = `${props.position[0] + 28}px`;
        this.wrapper.style.left = `${props.position[1]}px`;
    }
    initWrapper = () => {
        this.wrapper = document.querySelector(`.${containerClass}`);
        if (!this.wrapper) {
            this.wrapper = document.createElement("div");
            this.wrapper.className = "visbar-gui-color-picker-wrapper";
            document.body.appendChild(this.wrapper);
        }
        this.wrapper.innerHTML = "";  /* 新打开一个新的颜色选择器时会清除其他的颜色选择器: 排他性 */
    }
    render() {
        const { color, onChange } = this.props;
        return ReactDOM.createPortal(<SketchPicker className="gui-color-picker" color={color} onChange={onChange} />, this.wrapper);
    }
}

interface IColorPickerProps {
    default: string;
    [key: string]: any;
}
interface IColorPickerState {
    color: string;
    visible: boolean;
    position: [number, number]
}
export default class ColorPicker extends React.Component<IColorPickerProps, IColorPickerState> {
    wrapper: HTMLDivElement;
    constructor(props: IColorPickerProps) {
        super(props);
        this.state = {
            color: props.default,
            visible: false,
            position: [0, 0]
        };
    }
    showColorPicker = () => {
        const { visible } = this.state;
        const dom = ReactDOM.findDOMNode(this);
        const domStyle = dom.getBoundingClientRect();
        const top = domStyle.top;
        const left = domStyle.left;
        this.setState({ visible: !visible, position: [top, left] })
    }
    colorChangeHandle = (ev) => {
        const { onChange } = this.props;
        onChange && onChange(ev.hex)
        this.setState({ color: ev.hex });
    }
    render() {
        const { color, visible, position } = this.state;
        return <div className="visbar-gui-color-picker">
            <button onClick={() => this.showColorPicker()}>
                <span className="picker-color-dot" style={{background: color}}></span>
            </button>
            {visible && <ColorPickerBase position={position} color={color} onChange={this.colorChangeHandle} />}
        </div>
    }
}